<template>
  <h1>添加学生</h1>
  <h2>{{ num }}</h2>
  <h2>{{ store.num }}</h2>
  <button @click="add">+1</button>
  <button @click="reset">重置</button>
  <hr />
  <h2>{{ store.total1 }}</h2>
  <h2>{{ store.total2 }}</h2>
  <hr />
  <div v-for="(item, idx) in store.list" :key="item.id">
    <span>{{ idx }}</span> --
    <span>{{ item.title }}</span>
  </div>
  <button @click="pageHander(-1)">上一页</button>
  <button @click="pageHander(1)">下一页</button>
</template>

<script setup>
import useCnodeStore from "./store/useCnodeStore";
import { storeToRefs } from "pinia";
import { watchEffect, ref } from "vue";

// 如果直接解构出仓库中的状态，导致响应式失效
// 使用storeToRefs，激活响应式
const { num } = storeToRefs(useCnodeStore());
const store = useCnodeStore();
const page = ref(1);

const add = () => {
  // store.$patch({ num: store.num + 1 });
  store.addNum(10);
};

const reset = () => {
  store.$reset();
};

watchEffect(
  () => {
    store.getList({ page: page.value, limit: 5, tab: "ask" });
  },
  { flush: "pre" }
);

const pageHander = (num) => {
  if (page.value === 1 && num === -1) return;
  page.value += num;
};

watchEffect(() => {
  store.$subscribe((mutations, state) => {
    // console.log("mutations:", mutations);
    // console.log("state:", state);
    // todo someting
  });
});

watchEffect(() => {
  store.$onAction(({ name, after }) => {
    const st = Date.now();
    console.log(`${name} start`, st);
    after(() => {
      const et = Date.now();
      console.log(`${name} end`, et);
      console.log(`${name} 执行了：`, et - st);
    });
  });
});
</script>
